package com.mpush.tools.common;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class DateUtils {

	public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
	public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
	public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";

	public static final String SLASH_DATE_TIME_FORMAT = "yyyy/MM/dd HH:mm:ss";
	public static final String SLASH_DATE_FORMAT = "yyyy/MM/dd";
	public static final String FULL_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";

	private static final Map<String, String> DateFormater = new HashMap<>();

	static {
		DateFormater.put("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$", DEFAULT_DATE_TIME_FORMAT);
		DateFormater.put("^\\d{4}-\\d{1,2}-\\d{1,2}$", DEFAULT_DATE_FORMAT);

		DateFormater.put("^\\d{4}/\\d{1,2}/\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$", SLASH_DATE_TIME_FORMAT);
		DateFormater.put("^\\d{4}/\\d{1,2}/\\d{1,2}$", SLASH_DATE_FORMAT);

		DateFormater.put("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}.\\d{1,3}$", FULL_TIME_FORMAT);
	}

	private DateUtils() {

	}

	public static Date parse(String text, String pattern) {
		try {
			return DateFormatUtils.getInstance(pattern).parse(text);
		} catch (ParseException e) {
			return null;
		}
	}

	public static Date parse(final String text) {

		if (null == text) {
			return null;
		}

		final String source = text.trim();

		for (Map.Entry<String, String> entry : DateFormater.entrySet()) {
			if (source.matches(entry.getKey())) {
				return DateUtils.parse(source, entry.getValue());
			}
		}

		return null;
	}

	public static String format(Date date, String pattern) {

		return null != date ? DateFormatUtils.getInstance(pattern).format(date) : null;
	}

	public static String format(Date date) {
		return format(date, DEFAULT_DATE_TIME_FORMAT);
	}

}
